<HTML>
<HEAD>
<title>libjson Array Example</title>
<script type="text/javascript" src="scripts/shCore.js"></script>
<script type="text/javascript" src="scripts/shBrushCpp.js"></script>
	<link type="text/css" rel="stylesheet" href="styles/shCoreDefault.css"/>
	<script type="text/javascript">SyntaxHighlighter.all();</script>

</HEAD>
<BODY>
<h1>libjson Array Example</h1>
<p>This quick example will show you how to add an array to your JSON tree.</p>
<p><span id="more-120"></span></p>
<pre class="brush:cpp;wrap-lines:true">JSONNODE *n = json_new(JSON_NODE);
json_push_back(n, json_new_a(&quot;RootA&quot;, &quot;Hello World&quot;));
JSONNODE *c = json_new(JSON_ARRAY);
json_set_name(c, &quot;ArrayOfNumbers&quot;);
json_push_back(c, json_new_i(NULL, 16));
json_push_back(c, json_new_i(NULL, 42));
json_push_back(c, json_new_i(NULL, 128));
json_push_back(n, c);
json_char *jc = json_write_formatted(n);
printf(&quot;%s\n&quot;, jc);
json_free(jc);
json_delete(n);</pre>

<p>The result will look like this:</p>
<pre class="brush:cpp;wrap-lines:true">{
    &quot;RootA&quot; : &quot;Hello World&quot;,
    &quot;ArrayOfNumbers&quot; : [
        16,
        42,
        128
    ]
}</pre>
<p>The first line generates a new root node for us to work with. This node will contain the entire JSON structure we want to create. Note that, as mentioned in the documentation, any time you call a <em>json_new&#8230;</em> method, you are responsbile for freeing the memory allocated by the method. You can do this manually or by attaching the resulting node pointer to an existing node.</p>

<p>Line 2 creates a new JSON_STRING node, i.e. a node that will have a string value, and attaches the new node to the end of our original root node <em>n</em>. The <em>json_new_a</em> method will escape your string values when you go to write the final string.</p>
<p>Line 3 creates a new child node and this time we&#39;re declaring a type of JSON_ARRAY that states the node will contain a number of nameless children nodes. While it&#39;s possible to have different data types in the same array, you should keep them all the same and treat it as if it were a typed array. Note that you can have an array of JSON_NODE objects, so you&#39;re not limited to simple data types, just be aware that the array will ignore any node names if you have them set.</p>
<p>Lines 5 through 7 add values to the array, in this case they&#39;re all integer values. Because a JSON array cannot contain named values, the name parameter of <em>json_new_i</em> is set to NULL.</p>

<p>Line 8 appends the array to our root node.</p>
<p>9 and 10 retrieve the formatted JSON string and dump it to stdout.</p>
<p>11 frees memory allocated for our JSON string and 12 frees the entire tree structure.</p>

<p>Chris Larsen 2010-10-08</p>
<BODY>
</HTML>